use std::net::SocketAddr;

use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, Debug, Default)]
pub struct ServerConfig {
    pub network: NetworkConfig,
    pub param: ParamConfig,
}

#[derive(Deserialize, Serialize, Debug)]
pub struct NetworkConfig {
    pub host: String,
    pub port: u16,
}

#[derive(Deserialize, Serialize, Debug)]
pub struct ParamConfig {
    pub max_size: u32,
    pub min_size: u32,
}

impl Default for NetworkConfig {
    fn default() -> Self {
        Self {
            host: "127.0.0.1".to_string(),
            port: 3000,
        }
    }
}

// 将 NetworkConfig 转换为 SocketAddr
impl From<NetworkConfig> for SocketAddr {
    fn from(value: NetworkConfig) -> Self {
        format!("{}:{}", value.host, value.port).parse().unwrap()
    }
}

impl Default for ParamConfig {
    fn default() -> Self {
        Self {
            max_size: 3,
            min_size: 10,
        }
    }
}

impl ServerConfig {
    pub async fn load() -> Self {
        // let content = std::fs::read_to_string("conf/config.yml").unwrap();
        if let Ok(content) = tokio::fs::read_to_string("conf/config.yml").await {
            serde_yaml::from_str(&content).unwrap()
        } else {
            ServerConfig::default()
        }
    }
}
